/**
 * actionHelper 是进行数据调用和业务处理的操作
 *
 */

//  导入操作本地数据的类

import DataHelper from "./DataHelper";
import ItemData from "./../model/ItemData";
import Category from "./../model/CateEnum";

class ActionHelper {
  // 1负责处理数据
  dataHelper: DataHelper = new DataHelper("memberList", "id");
  // 存储本地取出来的数组 笔记数组
  memberList!: Array<ItemData>;

  constructor() {
    this.memberList = this.readData();
  }
  //读取分类

  getCategory(categoryId: Category): string {
    // console.log(Category);
    let arr = ["学习", "生活", "工作"];

    return arr[categoryId];
    // return Category[categoryId];
  }

  // 读取返回 itemData格式的数组
  readData(): Array<ItemData> {
    // 1先获取本地的数据
    let arr = this.dataHelper.readData();

    //2将数据转成 array itemData 的格式
    let memberList = arr.map((ele: any) => {
      let item: ItemData = new ItemData();

      item.id = ele.id;
      item.categoryId = ele.categoryId;
      item.title = ele.title;
      item.content = ele.content;
      item.createTime = ele.createTime;
      return item;
    });

    return memberList;
  }

  // 2.业务处理函数----------------------------------
  // 2.1 新增笔记 返回新增的笔记 id
  add(item: ItemData): number {
    //先保存到本地数据，返回具体的id
    let newId = this.dataHelper.addData(item);
    //添加到笔记 memberList 数组中
    this.memberList.push(item);
    //再把笔记数组保存到本地
    this.dataHelper.saveData(this.memberList);

    // 返回 笔记id
    return newId;
  }
  // 2.2 修改笔记
  edit(item: ItemData): void {
    //根据item 寻找对应的本地笔记的item
    let editItem: ItemData | undefined = this.memberList.find((ele) => {
      return ele.id == item.id;
    });

    // 将传入的值 替换editItem的值
    if (editItem != undefined) {
      editItem.categoryId = item.categoryId;
      editItem.content = item.content;
      editItem.title = item.title;

      // 保存 被修改的数组
      this.dataHelper.saveData(this.memberList);
    }
  }

  // 2.3 删除笔记
  remove(id: number): void {
    //
    //根据id 找到对应的笔记 index，删除
    let d_index = this.memberList.findIndex((item) => {
      return item.id == id;
    });
    if (d_index > -1) {
      this.memberList.splice(d_index, 1);
      //再保存被删除的数组
      this.dataHelper.saveData(this.memberList);
    }
  }
}

export default ActionHelper;
